<template>
    <a-spin tip="加载中..." :spinning="spinning">
        <div class="article-edit-content">
            <h2 v-if="pageType === 0" style="font-family: 幼圆;text-align: center;margin-bottom: 20px;font-weight: bold;">
                创作文章
            </h2>
            <h2 v-else-if="pageType === 1"
                style="font-family: 幼圆;text-align: center;margin-bottom: 20px;font-weight: bold;">创作文章</h2>

            <a-form ref="formRef" :rules="rules" :model="formState" style="max-width: 700px;margin: 0 auto;">
                <a-form-item name="title" label="标题">
                    <a-input v-model:value="formState.title" />
                </a-form-item>

                <a-form-item name="categoryId" label="分类">
                    <a-select v-model:value="formState.categoryId" placeholder="请选择">
                        <a-select-option v-for="item in categorys" :key="item.id" :value="item.id">
                            {{ item.categoryName }}
                        </a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item name="tagIds" label="标签">
                    <a-select v-model:value="formState.tagIds" mode="multiple" placeholder="请选择" allow-clear>
                        <a-select-option v-for="item in tags" :key="item.id" :value="item.id">
                            {{ item.tagName }}
                        </a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item name="remark" label="备注">
                    <a-input v-model:value="formState.remark" />
                </a-form-item>

                <a-form-item name="isComment" label="允许评论">
                    <a-switch v-model:checked="formState.isComment" :checked-value="1" :unChecked-value="0" />
                </a-form-item>

                <a-form-item name="status" label="状态">
                  <a-select class="select" v-model:value="formState.status">
                    <a-select-option :value="0">草稿</a-select-option>
                    <a-select-option :value="1">发布</a-select-option>
                    <a-select-option :value="2">下架</a-select-option>
                  </a-select>
                </a-form-item>

                <a-form-item name="thumbnail" label="标题图">
                    <a-upload v-model:file-list="fileList" :max-count="1" :custom-request="handleUpload"
                        :on-remove="fileRemove" :before-upload="beforeUpload" list-type="picture" accept="image/*">
                        <a-button>
                            <UploadOutlined />
                            点击上传
                        </a-button>
                    </a-upload>
                </a-form-item>
            </a-form>

            <div class="btn">
                <a-button @click="back">返回</a-button>
                <a-button type="primary" @click="submitForm()">保存</a-button>
            </div>

            <v-md-editor height="400px" width="100%" ref="editorRef" v-model="formState.mdContent" :autofocus="true"
                :left-toolbar="leftBar" :right-toolbar="rightBar" :disabled-menus="[]"
                @upload-image="handleUploadImage">
            </v-md-editor>
        </div>
    </a-spin>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { upload2 } from '@/api/file';
import { findCategoryList } from "@/api/category.js";
import { findTagList } from "@/api/tag.js";
import { addArticle, findArticleById, editArticle } from "@/api/article.js";

// 模块ID
const moduleId = '4';
const editorRef = ref(null);
// 路由相关
const router = useRouter()
const route = useRoute()
// 页面类型:0新增，1编辑
const pageType = parseInt(route.query.pageType);
//左侧工具栏
const leftBar = ref('undo redo clear h bold italic strikethrough quote ul ol table hr link image code');
//右侧工具栏
const rightBar = ref('preview sync-scroll fullscreen');
const formRef = ref(null);
// 文章ID
const articleId = ref(route.query.id);
// 表单信息
const formState = reactive({
    id: null,
    title: '',
    htmlContent: '',
    mdContent: '',
    categoryId: null,
    tagIds: [],
    isComment: 0,
    wordCount: 0,
    likeCount: 0,
    collectCount: 0,
    viewCount: 0,
    commentCount: 0,
    status: 2,
    isTop: 0,
    thumbnail: '',
    content: '',
    remark: '',
})
const spinning = ref(false);
const rules = {
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' }
    ],
    categoryId: [
        { required: true, message: '请选择分类', trigger: 'change' }
    ],
    tagIds: [
        { required: true, message: '请选择标签', trigger: 'change' }
    ]
}

// 标签列表
const tags = ref([])
// 分类列表
const categorys = ref([])
// 文件列表
const fileList = ref([])
const imgPath = ref('')

// 允许的图片类型
const allowTypes = [
    'image/jpeg',   // JPG/JPEG
    'image/png',    // PNG
    'image/webp',   // WebP
    'image/gif',    // GIF（支持动态图）
    'image/bmp',    // BMP
    'image/tiff',   // TIFF
    'image/svg+xml' // SVG（矢量图）
];
// 图片类型友好名称映射（用于错误提示）
const allowedTypeNames = {
    'image/jpeg': 'JPG/JPEG',
    'image/png': 'PNG',
    'image/webp': 'WebP',
    'image/gif': 'GIF',
    'image/bmp': 'BMP',
    'image/tiff': 'TIFF',
    'image/svg+xml': 'SVG'
};

// 获取标签
const getTags = () => {
    findTagList().then((res) => {
        if (res.code === 200) {
            tags.value = res.data;
        }
    }).catch((err) => {
    })
}
// 获取分类
const getCategorys = () => {
    findCategoryList().then(res => {
        if (res.code === 200) {
            categorys.value = res.data;
        }
    }).catch(err => {
    })
}
// 查询文章详情
const getArticleDetail = () => {
    spinning.value = true;
    findArticleById(articleId.value).then(res => {
        if (res.code === 200) {
            let data = res.data;
            Object.assign(formState, data.articleInfo);
            formState.tagIds = data.tagList.map(e => { return e.id });
            // pic
            fileList.value = [{
                uid: data.articleInfo.id,
                name: '缩略图',
                status: 'done',
                url: data.articleInfo.thumbnail,
            }];
        }
    }).catch(err => {
    }).finally(() => {
        spinning.value = false;
    });
}

// 生命周期钩子
onMounted(async () => {
    try {
        getTags();
        getCategorys();
        if (pageType === 0) {
            // 新增
          fileList.value = [];
        } else if (pageType === 1) {
            // 编辑
            getArticleDetail();
        }

    } catch (error) {
        message.error('文章加载失败')
        console.error(error)
    }
})

// 保存文章
const submitForm = async () => {
    formRef.value
        .validate()
        .then(() => {
            if (pageType == 0) {
                // 保存
                addArticle(formState).then(res => {
                    if (res.code === 200) {
                        message.success('文章保存成功')
                        router.push('/home')
                    } else {
                        message.error('文章保存失败')
                    }
                })
            } else if (pageType == 1) {
                // 编辑
                editArticle(formState).then(res => {
                    if (res.code === 200) {
                        message.success('文章修改成功')
                        const backPath = route.query.backPath;
                        if (backPath) {
                            router.push({
                                path: backPath
                            })
                        } else {
                            router.push({
                                path: '/home'
                            })
                        }
                    } else {
                        message.error(res.message || '文章修改失败')
                    }
                })
            }
        })
        .catch(error => {
            console.log('error', error);
        });
}
// 返回
const back = () => {
    const backPath = route.query.backPath;
    if (backPath) {
        router.push({
            path: backPath
        })
    } else {
        router.push({
            path: '/home'
        })
    }
}

const fileRemove = (file) => {
    fileList.value = fileList.value.filter(item => item.uid !== file.uid)
}

// 上传图片 - markdown
const handleUploadImage = async (event, insertImage, files) => {
    // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
    const formData = new FormData();
    formData.append('file', files[0]);
    formData.append('moduleId', props.moduleId);
    const res = await upload2(formData);
    if (res.data && res.data.code === 200 && res.data.data) {
        insertImage({
            url: res.data.data.fileAddress,
            desc: res.data.data.originName
        });
    } else {
        message.error('上传图片失败');
    }
};
// 上传图片
const handleUpload = ({ file, onSuccess, onError }) => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('moduleId', moduleId);

    upload2(formData).then(res => {
        res = res.data;
        if (res.code === 200) {
            formState.thumbnail = res.data.fileAddress;
            file.url = res.data.fileAddress;
            fileList.value[0].thumbnail = res.data.fileAddress;
            fileList.value[0].url = res.data.fileAddress;
            fileList.value[0].status = 'done';
            message.success('图片上传成功')
        }
    }).catch(err => {
        message.error('图片上传失败')
    })
}
// 上传前校验
const beforeUpload = (file) => {
    // 校验图片类型
    if (!allowTypes.includes(file.type)) {
        const allowedTypesText = allowTypes.map(type => allowedTypeNames[type] || type).join('、');
        message.warn(`请上传${allowedTypesText}格式的图片`);
        return false;
    }
    // 校验图片大小
    const isLt2M = file.size / 1024 / 1024 < 20
    if (!isLt2M) {
        message.error('图片大小不能超过2MB')
        return false;
    }
    return true;
}
</script>

<style scoped>
.article-edit-content {
    margin: 0 auto;
    /* margin-top: 100px; */
    padding: 20px;
    max-width: 1200px;

    .arrow-left {
        margin-top: 200px;
    }


    .btn {
        display: flex;
        justify-content: flex-end;
        margin-bottom: 10px;

        button:first-child {
            margin-right: 10px;
        }
    }
}

.upload-demo {
    margin-bottom: 16px;
}
</style>